package com.qianxin.ids.idam.am.authn.factors.cass.upsso.refreshToken;


import com.qianxin.ids.idam.am.authn.factors.cass.upsso.api.CassCommon;
import com.qianxin.ids.idam.am.session.api.entity.AuthnContext;
import lombok.Data;

import java.io.Serializable;
import java.util.Objects;

/**
 * @author xiongjianlin
 */
@Data
public class RefreshEntity implements Serializable {
    private String contextId;
    private String userId;
    private String userCode;
    private String token;
    private String session;
    private String instanceId;
    /**
     * token过期时间分钟。  最小不能低于窗口时间。
     */
    private Integer tokenExpireTime=30;
    /**
     * Token 具体过期时间（毫秒时间戳）
     */
    private long expireTime;
    private String refreshToken;
    /**
     *  提前刷新窗口（如过期前5分钟触发刷新）
     */
    private int refreshWindowMinutes = 5;

    public RefreshEntity() {
    }


    // 判断是否需要刷新 Token
    public boolean shouldRefresh() {
        long currentTimeMillis = System.currentTimeMillis();
        // 过期时间 - 刷新窗口时间 <= 当前时间 → 需要刷新
        return (expireTime - (refreshWindowMinutes * 60 * 1000L)) <= currentTimeMillis;
    }

    // 刷新后更新 Token 和过期时间
    public void updateToken(String newToken, int ttlMinutes) {
        this.refreshToken = newToken;
        this.expireTime  = System.currentTimeMillis() + ttlMinutes * 60 * 1000L;
    }

    public RefreshEntity(String contextId, String userId, String token, String session, String instanceId, Integer tokenExpireTime, long expireTime, String refreshToken, int refreshWindowMinutes) {
        this.contextId = contextId;
        this.userId = userId;
        this.token = token;
        this.session = session;
        this.instanceId = instanceId;
        this.tokenExpireTime = tokenExpireTime;
        this.expireTime = expireTime;
        this.refreshToken = refreshToken;
        this.refreshWindowMinutes = refreshWindowMinutes;
    }

    public RefreshEntity (AuthnContext authnContext){
        this.token = authnContext.getAttribute(CassCommon.TOKEN);
        this.session = authnContext.getAttribute(CassCommon.SESSION);
        this.instanceId = authnContext.getAttribute(CassCommon.INSTANCE);
        this.contextId = authnContext.getId();
        this.expireTime = authnContext.getAttribute(CassCommon.EXPIRETIME);
        this.userCode = authnContext.getAttribute(CassCommon.USER);
        // 暂时不用userId。 认证方法需要手动查询后才有。
//        this.setUserId(authnContext.getBizUserEntity().getId());
    }

    @Override
    public boolean equals(Object o) {
        if (o == null || getClass() != o.getClass()) return false;
        RefreshEntity entity = (RefreshEntity) o;
        return Objects.equals(contextId, entity.contextId);
    }

    @Override
    public int hashCode() {
        return Objects.hashCode(contextId);
    }
}
